package com.example.androidlearning2200.service;


import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import java.io.IOException;

/**
 * 在后台播放音乐的Service
 */
public class MusicService extends Service {

    private MediaPlayer mediaPlayer;

    /**
     * 用于绑定后与Service进行通信
     */
    public class MyBinder extends Binder {
        /**
         * 播放一首新的音乐
         *
         * @param resId
         */
        public void play(int resId) {
            try {
                mediaPlayer.reset();
                Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + resId);
                mediaPlayer.setDataSource(MusicService.this, uri);
                mediaPlayer.prepare();
                mediaPlayer.start();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        /**
         * 暂停当前正在播放的音乐
         */
        public void pause() {
            mediaPlayer.pause();
        }

        /**
         * 恢复播放暂停的音乐
         */
        public void replay() {
            mediaPlayer.start();
        }

        /**
         * 当前是否正在播放
         *
         * @return
         */
        public boolean isPlaying() {
            return mediaPlayer.isPlaying();
        }

        /**
         * 获取音乐时长
         *
         * @return
         */
        public int getMusicDuration() {
            return mediaPlayer.getDuration();
        }

        /**
         * 获取当前播放进度
         *
         * @return
         */
        public int getMusicProgress() {
            return mediaPlayer.getCurrentPosition();
        }

        /**
         * 设置播放进度
         *
         * @param position
         */
        public void setMusicProgress(int position) {
            mediaPlayer.seekTo(position);
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d("MessageService", "onBind");
        return new MyBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("MessageService", "onCreate");
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("MessageService", "onUnbind");
        mediaPlayer.pause();
        mediaPlayer.stop();
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        Log.d("MessageService", "onDestroy");
        super.onDestroy();
    }
}
